package com.df.happylearn.articlecontent;

import com.android.volley.VolleyError;
import com.df.happylearn.model.ArticleContentInfo;
import com.df.happylearn.request.DataProvider;
import com.df.happylearn.utils.CacheUtil;
import com.df.happylearn.utils.Constants;

/**
 * Created by dingfeng on 2016/5/24.
 */
public class ContentPresenter implements ContentContract.Presenter {

    private final ContentContract.View mContentView;
    private int articleId;
    private ArticleContentInfo articleContentInfo;
    private String KEY_CACHE;

    public ContentPresenter(ContentContract.View contentView, int articleId) {
        mContentView = contentView;
        this.articleId = articleId;
        KEY_CACHE = "article_cache_" + articleId;
        mContentView.setPresenter(this);
    }

    @Override
    public void start() {
        loadCacheData();
    }

    @Override
    public void loadCacheData() {
        articleContentInfo = (ArticleContentInfo) CacheUtil.getInstance().getArticleContentCache().getAsObject(KEY_CACHE);
        if (articleContentInfo != null) {
            mContentView.showContent(articleContentInfo);
        } else {
            loadArticleContent();
        }
    }

    @Override
    public void loadArticleContent() {
        DataProvider.getInstance().getArticleContent(articleId, new DataProvider.Callback<ArticleContentInfo>() {
            @Override
            public void onSuccess(ArticleContentInfo bean) {
                CacheUtil.getInstance().getArticleContentCache().put(KEY_CACHE, bean, Constants.CACHE_TIEM_ARTICLE);
                mContentView.showContent(bean);
            }

            @Override
            public void onError(VolleyError error) {
                mContentView.showLoadError();
            }
        });

    }

}
